package cn.z2huo.knowledge.concurrency.queue;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * <p>
 *
 * @author z2huo
 */
@Slf4j
class BlockingQueueTakeTest {

    private static final int QUEUE_CAPACITY = 5;

    @Getter
    private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);

    public static void main(String[] args) {
        BlockingQueueTakeTest test = new BlockingQueueTakeTest();

        boolean offerFlag = test.getQueue().offer("a");
        if (offerFlag) {
            log.info("offer element to queue success");
        }

        // 使用 remove、poll 不会因为队列中没有元素而阻塞
        log.info("remove from queue, value is {}", test.getQueue().remove());
        // 队列中没有元素，则抛出异常
        try {
            log.info("remove from queue, value is {}", test.getQueue().remove());
        } catch (Exception e) {
            log.error("remove from queue error, queue is empty");
        }

        boolean addFlag = test.getQueue().add("b");
        if (addFlag) {
            log.info("add element to queue success");
        }

        // 使用 remove、poll 不会因为队列中没有元素而阻塞
        log.info("poll from queue, value is {}", test.getQueue().poll());
        // 队列中没有元素，则返回 null
        log.info("poll from queue, value is {}", test.getQueue().poll());

        try {
            // 阻塞队列中没有元素，take() 方法会阻塞，直到有元素加入队列
            String take = test.getQueue().take();
            log.info("take from queue, value is {}", take);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

}
